package com.songcha.library_base.compose

import android.os.Bundle
import android.view.View
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.res.colorResource
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.LifecycleCoroutineScope
import androidx.lifecycle.lifecycleScope
import com.songcha.library_base.R
import com.songcha.library_base.interfaces.ILoadMoreData
import com.songcha.library_base.mvvm.base.BaseRefreshLoadMoreViewModel
import com.songcha.library_base.mvvm.base.BaseRefreshViewModel
import com.songcha.library_base.mvvm.base.BaseRepository
import com.songcha.library_common.util.dp2px
import com.songcha.library_compose_refresh.NestedScrollMode
import com.songcha.library_compose_refresh.UltraSwipeRefresh
import com.songcha.library_compose_refresh.indicator.SwipeRefreshHeader
import com.songcha.library_compose_refresh.indicator.classic.ClassicRefreshFooter
import com.songcha.library_compose_refresh.rememberUltraSwipeRefreshState
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


abstract class BaseComposeRefreshLoadMoreMvvmFragment<VM: BaseRefreshLoadMoreViewModel<out BaseRepository, out Any>>:BaseComposeRefreshMvvmFragment<VM>(),
    IComposeLoadMoreData {
    protected open lateinit var lazyListState:LazyListState
    private var footerHeight = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        viewModel.loadMore_state.observe(this){
            when(it){
                BaseRefreshLoadMoreViewModel.LoadMoreState.LOADMORE_SUCCESS-> onLoadMoreSuccess(viewModel.loadMoreStart,viewModel.loadMoreCount)
                BaseRefreshLoadMoreViewModel.LoadMoreState.LOADMORE_ERROR->onLoadMoreError(viewModel.loadMore_error!!)
                BaseRefreshLoadMoreViewModel.LoadMoreState.LOADMORE_NO_NETWORK->onLoadMoreNoNetwork()
                BaseRefreshLoadMoreViewModel.LoadMoreState.LOADMORE_CONNECT_ERROR->onLoadMoreConnectError()
                BaseRefreshLoadMoreViewModel.LoadMoreState.LOADMORE_NO_DATA->onLoadMoreNoData()
                BaseRefreshLoadMoreViewModel.LoadMoreState.LOADMORE_TIMEOUT->onLoadMoreTimeout()
                else -> {}
            }
        }

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
    }

    @Composable
    override fun RefreshView(content:@Composable () -> Unit){
        val srState = rememberUltraSwipeRefreshState()
        val refresh_state by viewModel.refresh_state.observeAsState()
        val loadMore_state by viewModel.loadMore_state.observeAsState()
        srState.isRefreshing = refresh_state==BaseRefreshViewModel.RefreshStateVM.REFRESHING
        srState.isLoading = loadMore_state==BaseRefreshLoadMoreViewModel.LoadMoreState.LOADINGMORE
        srState.isLoadNoData = loadMore_state==BaseRefreshLoadMoreViewModel.LoadMoreState.LOADMORE_NO_DATA

        listenLoadMoreSuccessToScroll()

        UltraSwipeRefresh(
            state = srState,
            onRefresh = {
                viewModel.onRefreshing()
                onGetData()
            },
            onLoadMore = {
                viewModel.onLoadingMore()
                onGetLoadMoreData()
            },
            modifier = Modifier.background(color = colorResource(id = com.songcha.library_common.R.color.white)),
            loadMoreEnabled = true,
            headerScrollMode = NestedScrollMode.Translate,
            footerScrollMode = NestedScrollMode.Translate,
            headerIndicator = {
                SwipeRefreshHeader(it, contentColor = colorResource(id = com.songcha.library_common.R.color.primary))
            },
            footerIndicator = {
                ClassicRefreshFooter(it)
            },
            onFooterLayout = {height ->
                footerHeight = height
            }
        ){
            content()
        }
    }

    protected open fun onGetLoadMoreData(){}

    override fun addRlstObserve() {
        viewModel!!.rlst.observe(this){
            if(it!=null && !viewModel.isLoadingMore && it.size>0){
                //initListData()
            }
        }
    }

    override fun onLoadingMore() {

    }

    override fun onRefreshing() {
        super.onRefreshing()
        //srl?.resetNoMoreData()
    }


    override fun onLoadMoreSuccess(start: Int, count: Int) {
        //srl?.finishLoadMore(true)
        //getListAdapter()?.notifyItemRangeChanged(start,count)
    }


    @Composable
    override fun listenLoadMoreSuccessToScroll(){
        lazyListState = rememberLazyListState()

        val loadMore_state by viewModel.loadMore_state.observeAsState()

        var lastTotalItemsCount by remember {
            mutableIntStateOf(0)
        }

        if(!lazyListState.isScrollInProgress){
            val totalItemCount = lazyListState.layoutInfo.totalItemsCount
            if(totalItemCount > lastTotalItemsCount){
                if(loadMore_state == BaseRefreshLoadMoreViewModel.LoadMoreState.LOADMORE_SUCCESS){
                    LaunchedEffect(lazyListState){
                        lazyListState.scrollBy(footerHeight.toFloat())
                    }
                }
                lastTotalItemsCount = totalItemCount
            }
        }
    }


    override fun onLoadMoreError(e: Throwable) {
        //srl?.finishLoadMore(false)
    }

    override fun onLoadMoreNoNetwork() {
        //srl?.finishLoadMore(false)
    }

    override fun onLoadMoreConnectError() {
        //srl?.finishLoadMore(false)
    }

    override fun onLoadMoreNoData() {
        //srl?.finishLoadMoreWithNoMoreData()
    }

    override fun onLoadMoreTimeout() {
        //srl?.finishLoadMore(false)
    }
}